package edu.chl.dat255.bluebanana.utils;

import java.lang.reflect.Method;

import com.android.internal.telephony.ITelephony;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;

public class PhoneCallReceiver extends BroadcastReceiver {
	private static final String TAG = "Phone call";
	private ITelephony telephonyService;
	private static boolean blockCalls = false;
	private TelephonyManager telephony;
	private SystemListener systemListener;
	private Class<?> c;
	private Method m;

	public static void setBlockCalls(boolean blockCalls) {
		PhoneCallReceiver.blockCalls = blockCalls;
	}

	/**
	 * Will only receive calls on the Android 2.2 platform (Froyo)
	 */

	@Override
	public void onReceive(Context context, Intent intent) {
		if (Build.VERSION.SDK_INT == Build.VERSION_CODES.FROYO
				&& blockCalls) {
			
			Log.v(TAG, "Receving phone call....");
			
			telephony = (TelephonyManager) context
			.getSystemService(Context.TELEPHONY_SERVICE);
			
			systemListener = new SystemListener();
			telephony.listen(systemListener, PhoneStateListener.LISTEN_CALL_STATE);
			
			try {
				c = Class.forName(telephony.getClass().getName());
				m = c.getDeclaredMethod("getITelephony");
				m.setAccessible(true);
				telephonyService = (ITelephony) m.invoke(telephony);
				telephonyService.silenceRinger();
				telephonyService.endCall();
				
			} catch (Exception e) {
				Log.e(TAG, "Error in PhoneCallReceiver");
			}
			
		} else if (!blockCalls) {
			Log.e(TAG, "Block phone calls is not activated");
		} else {
			Log.e(TAG, "Non-compatible version of Android");
		}
	}
}
